<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="adaptiveWidth" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="menuForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, ComponentTypes } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { list, saveOrUpdateMenu, getBtdAppList, getBtdResouceListByAppId } from './menu.api';
  import { useDrawerAdaptiveWidth } from '/@/hooks/base/useAdaptiveWidth';
  import { useI18n } from '/@/hooks/web/useI18n';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const { adaptiveWidth } = useDrawerAdaptiveWidth();
  const attrs = useAttrs();
  const isUpdate = ref(true);
  const menuType = ref(0);
  const isButton = (type) => type === 2;
  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate }] = useForm({
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    menuType.value = data?.record?.menuType;

    //获取下拉树信息
    const treeData = await list({});

    // 获取轻应用列表
    const resourceAppId = data.record?.menuResourceAppId || '';
    const btdAppList = await getBtdAppList();
    const formatBtdAppData = (data) => {
      return data.map((item) => {
        return {
          label: item.name,
          value: item.appId,
        };
      });
    };

    // 获取轻应用资源列表
    let btdResourceList: any = [];
    const formatBtdResourceList = async (appId) => {
      const result: any = [];
      const resources = await getBtdResouceListByAppId({ app_id: appId });
      if (resources[0]) {
        // 获取表单数据
        const formResource = resources[0]?.pageList.find((item) => item.formType === 0);
        if (formResource) {
          result.push({
            label: '表单',
            value: 'FORM',
            disabled: true,
            children: formResource.formList.map((item) => {
              return {
                // ...item,
                label: item.name.zh,
                value: item.formKey,
              };
            }),
          });
        }
        // 获取列表数据
        const listResource = resources[0]?.pageList.find((item) => item.formType === 1);
        if (listResource) {
          result.push({
            label: '列表',
            value: 'LIST',
            disabled: true,
            children: listResource.formList.map((item) => {
              return {
                // ...item,
                label: item.name.zh,
                value: item.formKey,
              };
            }),
          });
        }
        // 获取Vue数据
        const vueResource = resources[0]?.pageList.find((item) => item.formType === 4);
        if (vueResource) {
          result.push({
            label: 'Vue页面',
            value: 'VUE',
            disabled: true,
            children: vueResource.formList.map((item) => {
              return {
                // ...item,
                label: item.name.zh,
                value: item.formKey,
              };
            }),
          });
        }
      }
      return result;
    };
    if (resourceAppId) {
      btdResourceList = await formatBtdResourceList(resourceAppId);
    }

    // 获取资源类型
    function getResourceType(data, targetChildValue) {
      for (let i = 0; i < data.length; i++) {
        const parent = data[i];
        if (parent.children) {
          for (let j = 0; j < parent.children.length; j++) {
            const child = parent.children[j];
            if (child.value === targetChildValue) {
              return parent.value;
            }
          }
        }
      }
      return null;
    }
    // 整理轻应用路径
    function formatBtdUrl(type, appId, formKey, isIframe = false) {
      let prefix = `/frame`;
      let url;
      if (isIframe) {
        prefix = '';
      }
      switch (type) {
        case 'FORM':
          url = `${prefix}/apps/desktop/sapp/${appId}/sappId/${formKey}`;
          break;
        case 'LIST':
          url = `${prefix}/apps/desktop/sapp/${appId}/sappId/box/list/${formKey}`;
          break;
        case 'VUE':
          url = `${prefix}/apps/desktop/sapp/${appId}/sappId/${formKey}`;
          break;
      }
      if (isIframe) {
        url += '?header=none';
      }
      return url;
    }

    updateSchema([
      {
        field: 'parentId',
        componentProps: { treeData: translateMenu(treeData, 'name') },
      },
      {
        field: 'menuSourceType',
        componentProps: ({ formActionType }) => {
          const { clearValidate } = formActionType;
          return {
            options: [
              { label: '普通菜单', value: 'default' },
              { label: '轻应用菜单', value: 'btd' },
            ],
            async onChange(e) {
              if (e.target?.value === 'default') {
                setFieldsValue({ url: '' });
                setFieldsValue({ menuResourceAppId: '' });
                setFieldsValue({ menuResourceId: '' });
                setFieldsValue({ menuResourceType: '' });
                await clearValidate();
              }
            },
          };
        },
      },
      {
        field: 'menuResourceAppId',
        componentProps: ({ formActionType }) => {
          return {
            options: formatBtdAppData(btdAppList),
            // 选择应用Id, 获取资源列表
            onChange: async (appId) => {
              setFieldsValue({ menuResourceId: '' });
              await clearValidate();
              const { updateSchema } = formActionType;
              const btdResourceList = await formatBtdResourceList(appId);
              updateSchema([
                {
                  field: 'menuResourceId',
                  componentProps: {
                    treeData: btdResourceList,
                    // 选择资源Id, 设置资源类型 和 访问轻应用url
                    onChange: async (resourceId) => {
                      const type = getResourceType(btdResourceList, resourceId);
                      setFieldsValue({ menuResourceType: type });
                      setFieldsValue({ url: formatBtdUrl(type, appId, resourceId) });
                      setFieldsValue({ component: formatBtdUrl(type, appId, resourceId, true) });
                      await clearValidate();
                    },
                  },
                },
              ]);
            },
          };
        },
      },
      {
        field: 'menuResourceId',
        componentProps: { treeData: btdResourceList },
      },
      {
        field: 'name',
        label: isButton(unref(menuType)) ? '按钮/权限' : '菜单名称',
      },
      {
        field: 'url',
        required: !isButton(unref(menuType)),
        componentProps: {
          onChange: (e) => onUrlChange(e.target.value),
        },
      },
    ]);

    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      let values = { ...data.record };
      setFieldsValue(values);
      onUrlChange(values.url);
    }
    //按钮类型情况下，编辑时候清除一下地址的校验
    if (menuType.value == 2) {
      clearValidate();
    }
    //禁用表单
    setProps({ disabled: !attrs.showFooter });
  });
  //获取弹窗标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));
  //提交事件
  async function handleSubmit() {
    try {
      const values = await validate();
      // iframe兼容
      if (ComponentTypes.IFrame === values.component) {
        values.component = values.frameSrc;
      }
      setDrawerProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdateMenu(values, unref(isUpdate));
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  /** url 变化时，动态设置组件名称placeholder */
  function onUrlChange(url) {
    let placeholder = '';
    let httpUrl = url;
    if (url != null && url != '') {
      if (url.startsWith('/')) {
        url = url.substring(1);
      }
      url = url.replaceAll('/', '-');
      // 特殊标记
      url = url.replaceAll(':', '@');
      placeholder = `${url}`;
    } else {
      placeholder = '请输入组件名称';
    }
    updateSchema([{ field: 'componentName', componentProps: { placeholder } }]);
    //update-begin---author:wangshuai ---date:20230204  for：[QQYUN-4058]菜单添加智能化处理------------
    if (httpUrl != null && httpUrl != '') {
      if (httpUrl.startsWith('http://') || httpUrl.startsWith('https://')) {
        setFieldsValue({ component: httpUrl });
      }
    }
    //update-end---author:wangshuai ---date:20230204  for：[QQYUN-4058]菜单添加智能化处理------------
  }

  /**
   * 2024-03-06
   * liaozhiyang
   * 翻译菜单名称
   */
  function translateMenu(data, key) {
    if (data?.length) {
      const { t } = useI18n();
      data.forEach((item) => {
        if (item[key]) {
          if (item[key].includes("t('") && t) {
            item[key] = new Function('t', `return ${item[key]}`)(t);
          }
        }
        if (item.children?.length) {
          translateMenu(item.children, key);
        }
      });
    }
    return data;
  }
</script>
